@extends('admin.layout')
@section('body')

    <!-- 正文开始 -->
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 表格工具栏 -->
                <form class="layui-form toolbar" lay-filter="formSearch" id="formSearch">
                    <div class="layui-form-item" id="highSearchItem">
                        <div class="layui-inline">
                            <label class="layui-form-label">科室:</label>
                            <div class="layui-input-inline">
                                <x-ca.top-disease name="department_id" show-all="--请选择科室--" id="sltTopDisease"
                                                  lay-filter="topDisease"></x-ca.top-disease>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">疾病:</label>
                            <div class="layui-input-inline">
                                <select class="layui-input" name="disease_id" id="sltDisease">

                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">咨询客户:</label>
                            <div class="layui-input-inline">
                                <x-system.user name="custom_service_id" show-all="--咨询客户--"
                                               group="{{\App\Models\System\Group::CUSTOM_SERVICE}}"></x-system.user>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">来源媒体:</label>
                            <div class="layui-input-inline">
                                <x-ca.source name="source_id"></x-ca.source>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">预约方式:</label>
                            <div class="layui-input-inline">
                                <x-ca.consultation-way name="consultation_way_id"></x-ca.consultation-way>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">预约医生:</label>
                            <div class="layui-input-inline">
                                <x-ca.doctor name="yy_doctor_id" show-all="--所有--"></x-ca.doctor>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">咨询状态:</label>
                            <div class="layui-input-inline">
                                <x-code code="AB" name="consultation_type" show-all="--所有--"></x-code>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">话务员:</label>
                            <div class="layui-input-inline">
                                <x-system.user name="medical_id" show-all="--所有--"
                                               group="{{\App\Models\System\Group::CALLER}}"></x-system.user>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">年龄段:</label>
                            <div class="layui-input-inline">
                                <select name="age_range" class="layui-input">
                                    <option value="">--所有--</option>
                                    <option value="1">12岁以下</option>
                                    <option value="2">12-18岁</option>
                                    <option value="2">18岁以上</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">到诊状态:</label>
                            <div class="layui-input-inline">
                                <x-code name="status" code="AC" show-all="--所有--"></x-code>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">排序:</label>
                            <div class="layui-input-inline">
                                <select name="order_by" class="layui-input">
                                    <option value="">--默认--</option>
                                    <option value="1">预约到院时间</option>
                                </select>
                            </div>
                        </div>

                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">日期类型:</label>
                            <div class="layui-input-inline">
                                <select name="date_type" class="layui-input">
                                    <option value="1">登记日期</option>
                                    <option value="2">预约时间</option>
                                    <option value="3">预约来院时间</option>
                                    <option value="4">到诊时间</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">日期范围:</label>
                            <div class="layui-input-inline">
                                <input name="date_range" autocomplete="off" id="txtDateRange" class="layui-input"/>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">@lang('common.keyword'):</label>
                            <div class="layui-input-inline">
                                <input name="keyword" id="txtKeyword" class="layui-input"
                                       placeholder="电话，预约号，名字，微信"/>
                            </div>
                        </div>
                        <div class="layui-inline">&emsp;
                            <button class="layui-btn icon-btn" lay-filter="searchForm" lay-submit>
                                <i class="iconfont icon-ic_search"></i>@lang('common.search')
                            </button>
                            @auth('searchRepeat')
                            <a class="layui-btn" onclick="searchRepeat()">查重</a>
                            @endauth
                            <a class="layui-btn layui-btn-warm" onclick="layui.$('#highSearchItem').toggle()">高级</a>
                            <a class="layui-btn layui-btn-danger" onclick="location.href='?'">清理</a>
                            @auth('export')
                                <a class="layui-btn" onclick="exportData()">导出</a>
                            @endauth
                        </div>
                    </div>
                </form>
                <!-- 数据表格 -->
                <div class="layui-ls">
                    <table class="layui-table" lay-even lay-size="sm">
                        <tr>
                            <th>预约号</th>
                            <th>姓名</th>
                            <th>性别</th>
                            <th>年龄</th>
                            <th>电话(微信)</th>
                            <th>诊疗病种</th>
                            <th>状态</th>
                            <th>区域</th>
                            <th>话务员</th>
                            <th>来源</th>
                            <th>咨询员</th>
                            <th>登记时间</th>
                            <th>预约时间</th>
                            <th>预约到院时间</th>
                            <th>到院时间</th>
                            <th>是否有效</th>
                            <th>签到</th>
                            <th>回访</th>
                            <th>操作</th>
                        </tr>
                        <tbody>
                        @foreach($customers as $customer)
                            <tr onclick="itemClick(this)">
                                <th>{{$customer['id']}}</th>
                                <th>
                                    @if($customer['status']==4)
                                        <span style="color: red;">{{$customer['name']}}</span>
                                    @elseif($customer['status']==3)
                                        <span style="color: #2e59d3;">{{$customer['name']}}</span>
                                    @else
                                        {{$customer['name']}}
                                    @endif
                                </th>
                                <th>{{$customer['gender_text']}}</th>
                                <th>
                                    @empty($customer['age'])
                                        无
                                    @else
                                        {{$customer['age']}}
                                    @endempty
                                </th>
                                <th>{{$customer['mobile_encryption']}}({{$customer['weixin']}})</th>
                                <th>@empty($customer['disease_data'])
                                    @else
                                        @foreach($customer['disease_data'] as $disease)
                                            {{$disease['name']}}
                                        @endforeach
                                    @endempty
                                </th>
                                <th><label style="color:#16baaa;">{{$customer['consultation_type_text']}}</label></th>
                                <th>{{$customer['province_name']}}&nbsp;&nbsp;{{$customer['city_name']}}</th>
                                <th>
                                    @if($customer['medical_id'])
                                        <span class="btn-link"
                                              onclick="searchField('medical_id','{{$customer['medical_id']}}')">
                                            {{$customer['medical_name']}}
                                        </span>
                                    @else
                                        无
                                    @endif
                                </th>
                                <th>
                                    @if($customer['source_id'])
                                        <span class="btn-link"
                                              onclick="searchField('source_id','{{$customer['source_id']}}')">
                                            {{$customer['source_name']}}
                                        </span>
                                    @else
                                        无
                                    @endif
                                </th>
                                <th>

                                    @if($customer['custom_service_id'])
                                        <span class="btn-link"
                                              onclick="searchField('custom_service_id','{{$customer['custom_service_id']}}')">
                                            {{$customer['custom_service_name']}}
                                        </span>
                                    @else
                                        无
                                @endif
                                <th>
                                    <span class="btn-link"
                                          onclick="searchTimeField(1,'{{substr($customer['created_at'],0,10)}}')">
                                        {{$customer['created_at']}}
                                    </span>
                                </th>
                                <th>
                                    @if($customer['tady_yy_time'])
                                        <span class="btn-link"
                                              onclick="searchTimeField(2,'{{substr($customer['tady_yy_time'],0,10)}}')">
                                            {{ $customer['tady_yy_time']}}
                                        </span>
                                    @else
                                        无
                                    @endif
                                </th>
                                <th>@if($customer['yy_time'])
                                        <span class="btn-link"
                                              onclick="searchTimeField(3,'{{substr($customer['yy_time'],0,10)}}')">
                                            {{$customer['yy_time']}}
                                        </span>
                                    @else
                                        未预约
                                    @endif</th>
                                <th>
                                    @if($customer['jz_time']>0)
                                        <span class="btn-link"
                                              onclick="searchTimeField(4,'{{substr($customer['jz_time'],0,10)}}')">
                                            {{$customer['jz_time']}}
                                        </span>
                                    @else
                                        未到
                                    @endif
                                </th>
                                <th>
                                     {{$customer['effective_text']}}
                                </th>
                                <th>
                                    @switch($customer['status'])
                                        @case(3)
                                            <label style="color:#1e9fff;">已到</label>
                                            @break
                                        @case(2)
                                            @if($customer['yy_time']<date('Y-m-d'))
                                                <label style="color:#ff5722;">过期</label>
                                            @else
                                                <label style="color:#31bdec;">预约</label>
                                            @endif
                                            @break
                                        @case(1)
                                            <label style="color:#16b777;">登记</label>
                                            @break
                                        @case(4)
                                            <label style="color:#ff5722;">过期</label>
                                            @break
                                        @case(6)
                                            <label style="color:#16baaa;">线上签到</label>
                                            @break
                                    @endswitch
                                </th>
                                <th onclick="event.stopPropagation();">
                                    <button type="button" class="layui-btn layui-btn-xs"
                                            onclick="visit({{$customer['id']}},'{{$customer['name']}}【电话:{{$customer['mobile']}}】');">
                                        {{empty($customer['visit_data'])?0:count($customer['visit_data'])}}
                                    </button>
                                </th>
                                <td class="f-14 isshow" onclick="event.stopPropagation();">
                                    @if($customer['status']!=6&&$customer['status']!=3)
                                        @auth('arriving')
                                            <button type="button" class="layui-btn layui-btn-xs"
                                                    onclick="arriving('{{$customer['id']}}','{{$customer['name']}}','{{$customer['yy_doctor_id']}}')">
                                                签到
                                            </button>
                                        @endauth
                                        @auth('onlineArriving')
                                            <button type="button" class="layui-btn layui-btn-normal layui-btn-xs"
                                                    onclick="onlineArriving('{{$customer['id']}}','{{$customer['name']}}','{{$customer['yy_doctor_id']}}')">
                                                线上签到
                                            </button>
                                        @endauth
                                    @endif
                                    @auth('edit')
                                        <button type="button" class="layui-btn layui-btn-xs"
                                                onclick="edit('{{$customer['id']}}')"
                                                title="编辑">编
                                        </button>
                                    @endauth
                                    @auth('delete')
                                        <button type="button" class="layui-btn layui-btn-danger layui-btn-xs"
                                                onclick="common_opt('确定要删除吗？',{{$customer['id']}},'{{admin_url($baseRoute.'delete?')}}')"
                                                title="删除">删
                                        </button>
                                    @endauth
                                    @auth('detail')
                                        <button type="button" class="layui-btn layui-btn-normal layui-btn-xs" title="详情"
                                                onclick="show({{$customer['id']}})">详
                                        </button>
                                    @endauth
                                    @auth('swt')
                                        <button type="button" class="layui-btn layui-btn-xs" title="商务通"
                                                onclick="swt({{$customer['id']}},'{{$customer['name']}}')">商
                                        </button>
                                    @endauth
                                    @auth('spend')
                                        <button type="button" class="layui-btn layui-btn-xs" title="消费"
                                                onclick="spend({{$customer['id']}},'{{$customer['name']}}【电话:{{$customer['mobile']}}】');">
                                            消
                                        </button>
                                    @endauth
                                </td>
                            </tr>
                            <tr class="extend">
                                <td colspan="100">
                                    <div>
                                        <label for="">状态：</label>
                                        <span style="color:#16baaa;">
                                            {{$customer['status_text']}}
                                        </span>
                                    </div>
                                    <div>
                                        <label for="">费用：</label>
                                        <span style="color:#ff5722;">
                                            {{$customer['cost_money']}}
                                        </span>
                                    </div>
                                    <div>
                                        <label for="">来源网站：</label>
                                        <span>
                                            {{$customer['source_site']}}
                                        </span>
                                    </div>
                                    <div>
                                        <label for="">搜索词：</label>
                                        <span>
                                            {{$customer['source_search_keywords']}}
                                        </span>
                                    </div>
                                    <div>
                                        <label for="">IP地址：</label>
                                        <span>
                                            {{$customer['source_ip']}}
                                        </span>
                                    </div>
                                    <div>
                                        <label for="">成永久身份ID：</label>
                                        <span>
                                            {{$customer['source_consulting_page']}}
                                        </span>
                                    </div>
                                    <div>
                                        <label for="">购买词：</label>
                                        <span>
                                            {{$customer['gm_words']}}
                                        </span>
                                    </div>
                                    <div>
                                        <label for="">病情描述：</label>
                                        <span>
                                            {{$customer['disease_desc']}}
                                        </span>
                                    </div>
                                    <div>
                                        <label for="">客户回访：</label>
                                        <div style="margin-left: 150px;">
                                            @if(!empty($customer['visit_data']))
                                                @foreach($customer['visit_data'] as $visit)
                                                    <div style="color: #2e59d3;">【{{$visit['user_name']}}
                                                        】{{$visit['created_at']}}
                                                        &nbsp;&nbsp;{{$visit['content']}} </div>
                                                @endforeach
                                            @endif
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>

                    <div id="pager"></div>
                </div>
            </div>
        </div>
    </div>
@stop
@push('style')
    <style>
        .layui-table .extend {
            display: none;
        }

        #highSearchItem {
            display: none;
        }

        .layui-card-body .layui-table[lay-size=sm] td, .layui-card-body .layui-table[lay-size=sm] th {
            font-size: 12px;
            padding: 5px 5px;
        }

        .layui-btn + .layui-btn {
            margin-left: 0;
        }

        .table-btn + .table-btn {
            margin-left: 0;
        }

        .extend label {
            font-weight: bold;
            display: inline-block;
            text-align: right;
            width: 150px;
        }
    </style>
@endpush
@push('script')
    <script type="text/html" id="arrivingTpl">
        <div style="padding: 20px;">
            <div class="layui-form-item">
                <label class="layui-form-label">医生:</label>
                <div class="layui-input-block">
                    <x-ca.doctor class="yy_doctor" name="yy_doctor_id" show-all="--选择挂号医生--"></x-ca.doctor>
                </div>
            </div>
        </div>
    </script>

    <script type="text/html" id="visitTpl">
        <div style="padding: 20px;">
            <div class="layui-form-item">
                <label class="layui-form-label">回访内容:</label>
                <div class="layui-input-block">
                    <textarea placeholder="请输入回访内容" class="layui-textarea"></textarea>
                </div>
            </div>
            @if(\App\Models\System\Group::CUSTOM_SERVICE!=\App\Facade\AppContext::groupCode())
                <div class="layui-form-item">
                    <label class="layui-form-label">下次回访时间:</label>
                    <div class="layui-input-block">
                        <input type="text" name="hf_time" id="txtHfTime" placeholder="请输入发病时间"
                               class="layui-input icon-date"/>
                    </div>
                </div>
            @endif
        </div>
    </script>
    <script type="text/html" id="spendTpl">
        <div style="padding: 20px;" class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">是否消费:</label>
                <div class="layui-input-block">
                    <input type="radio" name="is_spend" value="0" title="否">
                    <input type="radio" name="is_spend" value="1" title="是" checked>
                </div>
            </div>
        </div>
    </script>
    <script type="text/javascript">
        layui.use(['laydate', 'form', 'laypage'], function () {
            layui.laydate.render({
                elem: '#txtDateRange'
                , range: '~' //或 range: '~' 来自定义分割字符
            });
            let searchParams = {!! json_encode($search) !!}
            layui.form.val('formSearch', searchParams);
            layui.form.on('select(topDisease)', function (item) {
                loadDisease(item.value);
            });

            layui.laypage.render({
                elem: 'pager',
                count: {{$customers->total()}},
                limit: {{$customers->perPage()}},
                curr: {{$customers->currentPage()}},
                //上一页、下一页 页数
                jump: function (obj, first) {
                    searchParams.page = obj.curr;
                    if (!first) {
                        //必须写在first下 否则会陷入死循环
                        //跳转的url
                        location.href = '?' + layui.$.param(searchParams);
                    }
                }
            });


            function loadDisease(value) {
                if (value) {
                    SystemUtil.ajax("{{admin_url('ca/disease/load')}}", "GET")
                        .setData({pid: value})
                        .send(1)
                        .done(function (res) {
                            let html = "<option value='0'>--请选择疾病--</option>";
                            res.data.forEach(function (item) {
                                html += `<option value='${item.id}'>${item.name}</option>`;
                            });
                            layui.$('#sltDisease').html(html);
                            layui.$('#sltDisease').val({{\Illuminate\Support\Arr::get($search,'disease_id',0)}});
                            layui.form.render("select");
                        });
                } else {
                    let html = "<option value='0'>--请选择疾病--</option>";
                    layui.$('#sltDisease').html(html);
                    layui.form.render("select");
                }
            }

            loadDisease(layui.$('#sltTopDisease').val());

            window.searchField = function (field, value) {
                searchParams.page = 1;
                searchParams[field] = value;
                location.href = '?' + layui.$.param(searchParams);
            }
            window.searchTimeField = function (date_type, date) {
                searchParams.page = 1;
                searchParams.date_type = date_type;
                searchParams.date_range = date + ' ~ ' + date;
                location.href = '?' + layui.$.param(searchParams);
            }

            window.exportData = function () {
                location.href = '{{admin_url($baseRoute.'export')}}?' + layui.$.param(searchParams);
            }
        });

        function itemClick(el) {
            layui.$('.layui-table .extend').not(layui.$(el).next()).hide();
            layui.$(el).next().toggle();
        }

        function show(id) {
            @auth('show')
            layer.full(SystemUtil.openUrl2({
                title: "详情",
                content: "{{admin_url($baseRoute.'detail')}}/" + id,
                area: ['400px', '280px']
            }));
            @endauth
        }

        /**
         * 公共操作方法
         * @param  {string} tip 操作提示文本
         * @param  {string} id  操作数据编号
         * @param  {string} url 操作执行地址
         * @return {[type]}     [description]
         */
        let common_opt = function (tip, id, url) {
            layer.confirm(tip, function () {
                SystemUtil.ajax(url, 'POST').setData({id}).send(3).then(res => {
                    location.reload();
                });
            });
        };

        function swt(id, name) {
            SystemUtil.openUrl2({
                title: "商务通-" + name,
                content: "{{admin_url($baseRoute.'swt')}}/" + id,
                area: ['600px', '600px']
            });
        }

        function searchRepeat() {
            let kw = layui.$('#txtKeyword').val();
            if (kw.length) {
                SystemUtil.openUrl(`查重${kw}`, "{{admin_url($baseRoute.'search-repeat')}}?kw=" + kw, ['800px', '600px']);
            }
        }

        function edit(id) {
            var index = SystemUtil.openUrl2({
                content: "{{admin_url($baseRoute.'edit')}}/" + id,
                title: "参数"
            });
            layer.full(index);
        }

        function arriving(id, title, doc_id) {
            layer.open({
                type: 1,
                title: '签到-' + title,
                btn: ['签到', '取消'],
                area: ['400px', '160px'],
                content: arrivingTpl.innerHTML,
                success: function (layero, index) {
                    SystemUtil.popViewSet(index);
                    layui.$(layero).find('.yy_doctor').val(doc_id);
                    layui.form.render('select');
                },
                yes: function (index, layero) {
                    let yy_doctor_id = layui.$(layero).find('.yy_doctor').val();
                    let loadIndex = layer.load(3);
                    SystemUtil.ajax("{{admin_url($baseRoute.'arriving')}}", 'POST').setData({
                        id,
                        yy_doctor_id
                    }).send(3).then(res => {
                        location.reload();
                    }).always(function () {
                        layer.close(loadIndex);
                        layer.close(index);
                    });
                }
            });
        }

        function spend(id, title) {
            layer.open({
                type: 1,
                title: '消费-' + title,
                btn: ['确定', '取消'],
                area: ['400px', '160px'],
                content: spendTpl.innerHTML,
                success: function (layero, index) {
                    SystemUtil.popViewSet(index);
                    layui.form.render();
                },
                yes: function (index, layero) {
                    let loadIndex = layer.load(3);
                    let is_spend = layui.$(layero).find('[name=is_spend]:checked').val();
                    SystemUtil.ajax("{{admin_url($baseRoute.'spend')}}/"+id+'/'+is_spend, 'POST').send(3).then(res => {
                        location.reload();
                    }).always(function () {
                        layer.close(loadIndex);
                        layer.close(index);
                    });
                }
            });
        }

        function onlineArriving(id, name) {
            common_opt(`【${name || ''}】是否线上签到？`, id, "{{admin_url($baseRoute.'online-arriving')}}")
        }

        function visit(id, title) {
            layer.open({
                type: 1,
                title: '回访信息-' + title,
                btn: ['回访', '取消'],
                area: ['400px', '350px'],
                content: visitTpl.innerHTML,
                success: function (layero, index) {
                    @if(\App\Models\System\Group::CUSTOM_SERVICE!=\App\Facade\AppContext::groupCode())
                    layui.laydate.render({
                        elem: '#txtHfTime',
                        trigger: 'click'
                    });
                    @endif
                },
                yes: function (index, layero) {
                    let content = layui.$(layero).find('.layui-textarea').val();
                    @if(\App\Models\System\Group::CUSTOM_SERVICE!=\App\Facade\AppContext::groupCode())
                    let hf_time = layui.$(layero).find('#txtHfTime').val();
                    @else
                    let hf_time = '';
                    @endif
                    let loadIndex = layer.load(3);
                    SystemUtil.ajax("{{admin_url($baseRoute.'visit')}}", 'POST').setData({
                        id,
                        content,
                        hf_time,
                    }).send(3).then(res => {
                        location.reload();
                    }).always(function () {
                        layer.close(loadIndex);
                        layer.close(index);
                    });
                }
            });
        }

        //流失
        function loss(id, title) {
            layer.open({
                type: 1,
                title: '流失-' + title,
                btn: ['流失', '取消'],
                area: ['400px', '160px'],
                content: lossTpl.innerHTML,
                success: function (layero, index) {
                    SystemUtil.popViewSet(index);
                    layui.form.render();
                },
                yes: function (index, layero) {
                    let reason = [];
                    layui.$(layero).find('input:checked').each(function () {
                        reason.push(this.value);
                    });
                    if (reason.length == 0) {
                        layer.msg('请选择流水原因');
                        return;
                    }
                    let loadIndex = layer.load(3);
                    SystemUtil.ajax("{{admin_url($baseRoute.'loss')}}", 'POST').setData({
                        id,
                        reason: reason.join(',')
                    }).send(3).then(res => {
                        location.reload();
                    }).always(function () {
                        layer.close(loadIndex);
                        layer.close(index);
                    });
                }
            });
        }

        function losssub(obj) {
            var vs = $('input[name="llinfo[]"]:checked').val();
            if (vs != null) {
                $.post("{:url('loss')}", $(obj).serialize(), function (data) {
                    if (data.status == 1) {
                        alert_success("操作成功", function () {
                            location.reload();
                        });
                    } else {
                        alert_error(data.info);
                    }

                });
            } else {
                alert_error('请选择原因');
            }
            return false;
        }

        //出院
        function leaveHospital(id, name) {
            common_opt(`确定【${name || ''}】出院了吗？`, id, "{{admin_url($baseRoute.'leave-hospital')}}")
        }

        //住院
        function hospitalization(id, name) {
            common_opt(`确定【${name || ''}】住院了吗？`, id, "{{admin_url($baseRoute.'hospitalization')}}")
        }
    </script>
@endpush
